package logic

import (
	"context"
	"encoding/json"
	"rent/cache"
	"rent/models"
	"time"

	"rent/rentrpc/internal/svc"
	"rent/rentrpc/rentrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCommentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommentListLogic {
	return &CommentListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CommentListLogic) CommentList(in *rentrpc.CommentListRequest) (*rentrpc.CommentListResponse, error) {
	// todo: add your logic here and delete this line
	var comment []models.CommentData
	result, _ := cache.Rdb.Get(cache.Ctx, "CommentList").Result()
	if result == "" {
		models.DB.Model(&models.Comment{}).
			Select("commodities.*, comments.content").
			Joins(" LEFT JOIN commodities ON comments.commodity_id = commodities.id").
			Order("comments.created_at desc").
			Where("comments.commodity_id=?", in.CommodityId).
			Find(&comment)
		marshal, _ := json.Marshal(comment)
		cache.Rdb.Set(cache.Ctx, "CommentList", marshal, time.Minute*15)
	} else {
		json.Unmarshal([]byte(result), &comment)
	}
	var commentDatas []*rentrpc.CommentData
	for _, data := range comment {
		commentData := rentrpc.CommentData{
			Title:   data.Title,
			Class:   data.Class,
			Price:   float32(data.Price),
			Details: data.Details,
			Content: data.Content,
		}
		commentDatas = append(commentDatas, &commentData)
	}
	return &rentrpc.CommentListResponse{
		List: commentDatas,
	}, nil
}
